<template>
  <div class="login">
    <el-card shadow="hover">
      <template #header>
        <div class="blog">abc</div>
      </template>
      <el-form :rules="rules" :model="user" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="user.username" prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="user.password" prefix-icon="Lock" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin(loginFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { setToken } from '@/utils/auth'
import type { ElForm } from 'element-plus'
import { login } from '@/api/login'

type FormInstance = InstanceType<typeof ElForm>

const router = useRouter()
const route = useRoute()

const loginFormRef = ref<FormInstance>()

const redirect = ref()

const user = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
})

onMounted(() => {
  redirect.value = route.query.redirect ? route.query.redirect : "/home"
})

const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const valid = await formEl.validate()
  if (!valid) return false
  const data = await login(user)
  setToken(data.token)
  router.replace(redirect.value || "/")
}
</script>
<style lang="sass" scoped>

.login
  min-width: 400px
  height: 90vh
  display: flex
  justify-content: center
  align-items: center
  background-color: #fff

.el-button
  width: 100%

.blog
  text-align: center

.el-card
  min-width: 300px
  padding: 0px 30px 0px
  border-radius: 6px
</style>